<?php

class Admin
{
    private $post = false;
    private $_db;


    public function __construct() 
    {
        if (isset ($_POST['login']) && isset($_POST['password']))
        {
            $this->post = true;
        }  
        $this->_db = Db::getInstance();
        session_start();
    }
    
    public function checkAdmin()
    {
        if ($this->post)
        {
            $this->checkForm();
        }
        
        $this->checkSession();
    }
    
    private function checkForm()
    {
        $nick = mysql_real_escape_string($_POST['login']);
        $password = md5(mysql_real_escape_string($_POST['password']));
        //validation
        //var_dump($nick);
        $sel = $this->_db->qr("select * from `admins` where `nickname` = '".$nick."'");
        //var_dump($sel);
        if ($sel != null)
        {
            if ($sel[0]['password'] !== $password)
            {
                $this->loginForm(array('validation'=>'Неверное имя пользователя или пароль'));
            }
            else
            {
                $_SESSION['admin'] = $sel[0]['nickname'];
                $_SESSION['roles'] = $sel[0]['roles'];
            }
        }
        else
        {
            $this->loginForm(array('validation'=>'Неверное имя пользователя или пароль'));
        }
    }
    
    private function checkSession()
    {
        if (!isset ($_SESSION['admin']))
        {
            $this->loginForm();
        }
    }
    
    private function loginForm($data=null)
    {
        $tpl = new TemplateAdmin('login', $data);
        $tpl->onlyView();
        exit;
    }
    
}